package life.mahu.community.controller;

import life.mahu.community.dto.AccessTokenDTO;
import life.mahu.community.dto.GithubAndMayunUser;
import life.mahu.community.model.User;
import life.mahu.community.provider.GithubProvider;
import life.mahu.community.provider.MayunProvider;
import life.mahu.community.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Controller
@Slf4j
public class AuthorizeController {

    @Autowired
    private GithubProvider githubProvider;

    @Autowired
    private MayunProvider mayunProvider;

    @Autowired
    private Environment env;

    @Autowired
    private UserService userService;

    @GetMapping("/callback")
    public String callback(@RequestParam(name = "code") String code,
                           @RequestParam(name = "type") String type,
                           @RequestParam(name = "userId", required = false) Long userId,
                           HttpServletRequest request,
                           HttpServletResponse response,
                           Model model) {
        AccessTokenDTO accessTokenDTO = new AccessTokenDTO();
        accessTokenDTO.setCode(code);
        String accessToken = null;
        GithubAndMayunUser githubAndMayunUser = null;
        if ("mayun".equals(type)) {
            accessTokenDTO.setClient_id(env.getProperty("mayun.client.id"));
            accessTokenDTO.setClient_secret(env.getProperty("mayun.client.secret"));
            if(userId!=null)
                accessTokenDTO.setRedirect_uri(env.getProperty("callback.uri").concat("?type=mayun&userId=").concat(userId.toString()));
            else
                accessTokenDTO.setRedirect_uri(env.getProperty("callback.uri").concat("?type=mayun"));
            accessToken = mayunProvider.getAccessToken(accessTokenDTO);
            githubAndMayunUser = mayunProvider.getUser(accessToken);
        } else {
            accessTokenDTO.setClient_id(env.getProperty("github.client.id"));
            accessTokenDTO.setClient_secret(env.getProperty("github.client.secret"));
            if(userId!=null)
                accessTokenDTO.setRedirect_uri(env.getProperty("callback.uri").concat("?type=github&userId=").concat(userId.toString()));
            else
                accessTokenDTO.setRedirect_uri(env.getProperty("callback.uri").concat("?type=github"));
            accessToken = githubProvider.getAccessToken(accessTokenDTO);
            githubAndMayunUser = githubProvider.getUser(accessToken);
        }
        if (githubAndMayunUser != null && githubAndMayunUser.getId() != null) {
            if (userId != null) {
                if (!userService.isBind(String.valueOf(githubAndMayunUser.getId()), type)) {//如果该第三方没有绑定则将该第三方账户与该主用户进行绑定
                    userService.bind(userId, Long.valueOf(githubAndMayunUser.getId()), githubAndMayunUser.getHtmlUrl(), githubAndMayunUser.getName(), githubAndMayunUser.getAvatarUrl(), type);
                    return "redirect:/profile/escrowAccount";
                }else {
                    model.addAttribute("githubClientId",env.getProperty("github.client.id"));
                    model.addAttribute("mayunClientId", env.getProperty("mayun.client.id"));
                    User user = (User) request.getSession().getAttribute("user");
                    model.addAttribute("userInfo",user);
                    model.addAttribute("escrowAccount",userService.getEscrowAccount(user));
                    model.addAttribute("section", "escrowAccount");
                    model.addAttribute("sectionName", "第三方账户");
                    model.addAttribute("error",1);
                    return "profile";
                }
            }
            if (userService.isBind(String.valueOf(githubAndMayunUser.getId()), type)) {//判断该第三方登陆有没有绑定主用户
                //如果绑定了则直接让其登陆
                String token = UUID.randomUUID().toString();
                userService.login(String.valueOf(githubAndMayunUser.getId()), "github".equals(type) ? 1 : 2, token, null, githubAndMayunUser);
                Cookie cookie = new Cookie("token", token);
                cookie.setMaxAge(60 * 60 * 24 * 30 * 6);
                response.addCookie(cookie);
                return "redirect:/";
            } else {//如果没有绑定则跳转到绑定页面让其绑定
                model.addAttribute("thirdPartData", githubAndMayunUser);
                model.addAttribute("witchGit", type);
                return "bind";
            }
        } else {
            log.error("callback get github error,{}", githubAndMayunUser);
            // 登录失败，重新登录
            return "redirect:/";
        }
    }

    @GetMapping("/logout")
    public String logout(HttpServletRequest request,
                         HttpServletResponse response) {
        request.getSession().removeAttribute("user");
        Cookie cookie = new Cookie("token", null);
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        return "redirect:/";
    }
}
